package com.exam.user.controller;

import com.alibaba.fastjson.JSON;
import com.exam.common.entity.Request;
import com.exam.common.entity.StatusCode;
import com.exam.common.exception.ExamException;
import com.exam.user.pojo.User;
import com.exam.user.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.http.HttpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.server.Session;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.HashMap;

/**
 * @ClassName : UserController
 * @Description :
 * @Author : WHB
 */

@RestController
@Api(description = "用户API接口")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 校验数据
     * @param data
     * @param type
     * @return
     */
    @GetMapping("/check/{data}/{type}")
    @ApiOperation(value="校验数据", notes="校验数据")
    public Request checkData(@PathVariable("data") String data, @PathVariable("type") Integer type  ) {
        return userService.checkData(data, type);
    }

    /**
     * 发送短信
     * @param data
     */
    @PostMapping("code")
    @ApiOperation(value="发送短信", notes="发送短信")
    public ResponseEntity<Void> sendCode(@RequestBody HashMap<String,String> data){
        String phone = data.get("phone");
        System.out.println(phone);
        userService.sendCode(phone);
        return ResponseEntity.ok().build();
    }

    /**
     * 用户注册
     * @param user
     * @param code
     * @return
     */
    @PostMapping("register")
    @ApiOperation(value="用户注册", notes="用户注册")
    public Request register(@Valid User user,BindingResult result, @RequestParam("code") String code){
        //  输入有误，返回错误信息
        if (result.hasFieldErrors()){
            return new Request(false,400,result.getFieldError().getDefaultMessage());
        }
        return userService.register(user,code);
    }


    /**
     * 根据用户名和密码查询用户
     * @param username
     * @param password
     * @return
     */
    @GetMapping("/query")
    public ResponseEntity<User> queryUser(@RequestParam("username") String username,
                             @RequestParam("password") String password
    ) throws Exception {
        return ResponseEntity.ok(userService.queryUser(username,password));
    }

    @GetMapping("/id")
    public ResponseEntity<User> queryUserById(@RequestParam("id") Long id
    ) throws Exception {
        return ResponseEntity.ok(userService.queryUserById(id));
    }
//    @PutMapping("/role/{id}")
//    public Request setRole(@PathVariable("id") Long id){
//
//    }
}
